package com.example.whm;



import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.holoeverywhere.LayoutInflater;
import org.holoeverywhere.app.Application;
import org.holoeverywhere.app.Fragment;
import org.holoeverywhere.preference.SharedPreferences;
import org.holoeverywhere.widget.AdapterView;
import org.holoeverywhere.widget.ListView;
import org.holoeverywhere.widget.Toast;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.example.whm.MyPreOrderFragment.adapter;
import com.example.whm.OneFragment.PageAdapter;
import com.example.whm.model.Carousel;
import com.example.whm.model.GalleryModel;
import com.example.whm.model.IndexP;
import com.example.whm.model.PreOrder;
import com.example.whm.model.ZaoDian;
import com.viewpagerindicator.CirclePageIndicator;

public class OneFragmentNormal extends Fragment {

	private AQuery aq;
	private AQuery aq2;
	
	private String topic;
	FragmentManager fm;
	private ViewPager pager_carousel;
	 CirclePageIndicator Indicator;
	 PageAdapter adapter;
	 IndexP index;
	 ListView list;
		private ViewPager pager_zaodian;
		private ViewPager pager_xiawucha;
		private ViewPager pager_shaokao;
		private ViewPager pager_xianguo;
		private ViewPager pager_xiaochi;
		private ViewPager pager_tianping;
		 ScheduledExecutorService t;
		
		

    @Override
 	public View onCreateView(LayoutInflater inflater, ViewGroup container,
 			Bundle savedInstanceState) {
     	View view = inflater.inflate(R.layout.one_layout_normal, container, false);  
     	aq=new AQuery(getActivity(), view);
    	 pager_carousel = (ViewPager)view.findViewById(R.id.one_layout_carousel_pager);
    	 pager_zaodian = (ViewPager)view.findViewById(R.id.one_layout_zaodian_gallery);
    	 pager_xiawucha = (ViewPager)view.findViewById(R.id.one_layout_xiawucha_gallery);
    	 pager_shaokao = (ViewPager)view.findViewById(R.id.one_layout_shaokao_gallery);
    	 pager_xianguo = (ViewPager)view.findViewById(R.id.one_layout_xianqie_gallery);
    	 pager_xiaochi = (ViewPager)view.findViewById(R.id.one_layout_xiaochi_gallery);
    	 pager_tianping = (ViewPager)view.findViewById(R.id.one_layout_tianping_gallery);
    	
      	// Pager2 = (ViewPager)view.findViewById(R.id.one_layout_pager);
          Indicator = (CirclePageIndicator)view.findViewById(R.id.one_layout_carousel_indicator);
          index=JSONObject.parseObject(getArguments().getString("data"), IndexP.class);
     	
     	
     	return view;
 	}
 
    


	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		System.out.println("OneFragmentNormal onDestroy");
	}



	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		System.out.println("OneFragmentNormal onPause");
	}


	
	Handler handler = new Handler() {  
        public void handleMessage(android.os.Message msg) {  
        	int index=pager_carousel.getCurrentItem();
			//System.out.println("pager_carousel run index="+index); 
			if (index==pager_carousel.getAdapter().getCount()-1) {
				pager_carousel.setCurrentItem(0);
			}else{
				pager_carousel.setCurrentItem(index+1);
			}
        };  
    };  
	
	
	
	
	// Timer t;

	 @Override  
	 public    void onStart() {  
		   super.onStart();  
	        t = Executors.newSingleThreadScheduledExecutor();  
	        // 当Activity显示出来后，每两秒钟切换一次图片显示  
	         
	        t.scheduleAtFixedRate(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					handler.obtainMessage().sendToTarget();
				}
			}, 1, 5, TimeUnit.SECONDS);  
		 // t=new Timer();
		/* t.schedule(new TimerTask() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				handler.obtainMessage().sendToTarget();;
			}
		}, 1000, 2000);  */
	     
	    } 
	  
	    @Override  
	    public   void onStop() {  
	    	System.out.println("OneFragmentNormal onStop");
	        t.shutdown();  	        
	         //t.cancel();
	    	super.onStop();  
	    }  
	
	

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		
		  fm = getChildFragmentManager();
		//  List<String> l=new ArrayList<String>();
		//  for (int i = 0; i < 8; i++) {
		//	l.add(String.valueOf(i));
		//}
		   adapter = new PageAdapter(fm,index.getCarousel());
		   pager_carousel.setAdapter(adapter);		   
		   Indicator.setViewPager(pager_carousel);
		
		   if (index.getMap().containsKey("zaodian")) {
			   aq.find(R.id.one_layout_zaodian).visible();
			   List<GalleryModel> l=list2gm(index.getMap().get("zaodian"));
			   pager_zaodian.setAdapter(new PageAdapter2(fm,l,pager_zaodian.getId()));			   
			   aq.find(R.id.one_layout_text_zaodian_label).text(String.valueOf(l.size()));
			   aq.find(R.id.one_layout_text_zaodian_select_label).text(String.valueOf(1));
		  }
		   if (index.getMap().containsKey("xiawucha")) {
			  // System.out.println("######## JSONObject.toJSONString(list2gm(index.getMap().get xiawucha=="+JSONObject.toJSONString(list2gm(index.getMap().get("xiawucha")), true));
			   aq.find(R.id.one_layout_xiawucha).visible();
			   List<GalleryModel> l=list2gm(index.getMap().get("xiawucha"));
			   pager_xiawucha.setAdapter(new PageAdapter2(fm,l,pager_xiawucha.getId()));
			   aq.find(R.id.one_layout_text_xiawucha_label).text(String.valueOf(l.size()));
			   aq.find(R.id.one_layout_text_xiawucha_select_label).text(String.valueOf(1));
		  }
		   if (index.getMap().containsKey("xianguo")) {
			   aq.find(R.id.one_layout_xianguo).visible();
			   List<GalleryModel> l=list2gm(index.getMap().get("xianguo"));
			   pager_xianguo.setAdapter(new PageAdapter2(fm,l,pager_xianguo.getId()));
			   aq.find(R.id.one_layout_text_xianqie_label).text(String.valueOf(l.size()));
			   aq.find(R.id.one_layout_text_xianqie_select_label).text(String.valueOf(1));
		   }
		   if (index.getMap().containsKey("shaokao")) {
			   aq.find(R.id.one_layout_shaokao).visible();
			   List<GalleryModel> l=list2gm(index.getMap().get("shaokao"));
			   pager_shaokao.setAdapter(new PageAdapter2(fm,l,pager_shaokao.getId()));
			   aq.find(R.id.one_layout_text_shaokao_label).text(String.valueOf(l.size()));
			   aq.find(R.id.one_layout_text_shaokao_select_label).text(String.valueOf(1));
		   }
		   if (index.getMap().containsKey("xiaochi")) {
			   aq.find(R.id.one_layout_xiaochi).visible();
			   List<GalleryModel> l=list2gm(index.getMap().get("xiaochi"));
			   pager_xiaochi.setAdapter(new PageAdapter2(fm,l,pager_xiaochi.getId()));
			   aq.find(R.id.one_layout_text_xiaochi_label).text(String.valueOf(l.size()));
				aq.find(R.id.one_layout_text_xiaochi_select_label).text(String.valueOf(1));
		   }
		   if (index.getMap().containsKey("tianping")) {
			   aq.find(R.id.one_layout_tianping).visible();
			   List<GalleryModel> l=list2gm(index.getMap().get("tianping"));
			   pager_tianping.setAdapter(new PageAdapter2(fm,l,pager_tianping.getId()));
			   aq.find(R.id.one_layout_text_tianping_label).text(String.valueOf(l.size()));
				aq.find(R.id.one_layout_text_tianping_select_label).text(String.valueOf(1));
		   }
		   		  
		   

		
		 
		  
		//init();
		
	}

	
	public  class PageAdapter extends FragmentStatePagerAdapter{

		List<Carousel> data;
		public PageAdapter(FragmentManager fm,List<Carousel> da) {
			super(fm);
			this.data=da; 
		}
       
		
		@Override
		public Fragment getItem(int pos) {
			
			//AQUtility.debug("primary", topics[pos]);
			//TwoFragmentItem f=new TwoFragmentItem();
			Bundle args = new Bundle();
			args.putSerializable("carousel", data.get(pos)); 
		/*	args.putString("id", data.get(pos).getId());
			args.putInt("pos", pos);
			if (pos==0) {
				
				args.putString("result", result);
			}*/
			OneFragmentCarousel fragment = (OneFragmentCarousel) Fragment.instantiate(OneFragmentCarousel.class, args);			
			return fragment;
			
		}

		@Override
		public int getCount() {
			return data.size();
		}
		

		
		
	}	
	
	public  class PageAdapter2 extends FragmentStatePagerAdapter{

		List<GalleryModel> data;
		int id;
		public PageAdapter2(FragmentManager fm,List<GalleryModel> da,int id) {
			super(fm);
			this.data=da; 
			this.id=id; 
		}
       
		
		@Override
		public Fragment getItem(int pos) {
			
			//AQUtility.debug("primary", topics[pos]);
			//TwoFragmentItem f=new TwoFragmentItem();
			Bundle args = new Bundle();
			args.putSerializable("gallery", data.get(pos)); 
		/*	args.putString("id", data.get(pos).getId());
			args.putInt("pos", pos);
			if (pos==0) {
				
				args.putString("result", result);
			}*/
			OneFragmentGallery fragment = (OneFragmentGallery) Fragment.instantiate(OneFragmentGallery.class, args);			
			return fragment;
			
		}

		
		
		@Override
		public void setPrimaryItem(ViewGroup container, int position,
				Object object) {
			// TODO Auto-generated method stub
		    set_tag(position, id); 
			super.setPrimaryItem(container, position, object);
		}


		@Override
		public int getCount() {
			return data.size();
		}
		

		
		
	}		
	

/*public void init(){
	
	  String url="http://"+Whm_app.api_url+":9000/api/user_preorder";
	  AjaxCallback<String> cb = new AjaxCallback<String>();        
	  cb.url(url).type(String.class).weakHandler(this, "ui");
	  SharedPreferences sp=((Application)getActivity().getApplication()).getSharedPreferences("whm",Context.MODE_PRIVATE);
  	String cookiename=sp.getString("cookie_name",null);
  	String cookievalue=sp.getString("cookie_value",null);
  	if (cookiename!=null&&cookievalue!=null) {
  		cb.cookie(cookiename,cookievalue);               
	}
	  aq.ajax(cb);
  }

  public void ui(String url, String r, AjaxStatus status){
	
	  System.out.println("ui  s="+r); 
	  if (status.getCode()==200) {
		 
		  
		  final String s=r;
		  new Thread( new Runnable() {
			  @Override
			public void run() {
				  // String s1= JSON.parseObject(s).getString("users");
				  
				  String mapr= JSON.parseObject(s).getString("mapr");
				  String listj= JSON.parseObject(s).getString("list");
				  map= JSON.parseObject(mapr, Map.class);
				  
				  boxs= JSON.parseArray(listj, PreOrder.class);
				  System.out.println("boxs.size()========="+boxs.size());
				
				  getActivity().runOnUiThread(new Runnable() {
					  
					  @Override
					  public void run() {
						  Toast.makeText(getActivity(), "boxs.size()="+boxs.size(), 1000).show();
						  if (isload) {
							  show_dialog(false);
							 
							  adap.setList(boxs);
							  adap.notifyDataSetChanged();
						}else{		
							isload=true;
						  aq2.id(R.id.progress).gone();
						//  aq2.id(R.id.four_layout_line).visible();
						  
						//   list=(ListView) aq2.id(R.id.myorder_fragment_listview).getListView();
						  View v=getActivity().getLayoutInflater().inflate(R.layout.four_layout_header, null);
						  View v2=getActivity().getLayoutInflater().inflate(R.layout.four_layout_footer, null);
						   AQuery a=new AQuery(v);
						  AQuery a2=new AQuery(v2);
						  a.id(R.id.four_layout_contact_name).text(add.getContact_name());
						  a.id(R.id.four_layout_contact_phone).text(add.getPhone());
						  a.id(R.id.four_layout_contact_addr).text(add.getDetail_address());
						  a2.find(R.id.four_layout_btn_sure).clicked(MyOrderFragment.this); 
						   radioButtonGroup=(RadioGroup) a.find(R.id.four_layout_pay).getView();
						  list.addHeaderView(v);
						  list.addFooterView(v2);
						 
						  adap=new adapter(boxs);
						  aq2.id(R.id.myorder_fragment_listview).adapter(adap);
						  aq2.id(R.id.myorder_fragment_listview).itemClicked(MyPreOrderFragment.this);
						  aq2.id(R.id.myorder_fragment_listview).getListView().setOnItemLongClickListener(MyPreOrderFragment.this);
						
						
						
						
						}
						  
						  
						  
						  
						  
						  
						  
						  
						  
						  
						  
						  //Utility.setListViewHeightBasedOnChildren(list);
					  }
				  });
			  }
		  }).start();
			
		  
	}else{
		Toast.makeText(getActivity(), "request error", 1000).show();
		
	}
	  
  }*/



public void  set_tag(int pos,int id){
	int index=pos+1;
	switch (id) { 
	case R.id.one_layout_zaodian_gallery:	
	//	aq.find(R.id.one_layout_text_zaodian_label).text(String.valueOf(count));
		aq.find(R.id.one_layout_text_zaodian_select_label).text(String.valueOf(index));
		break;
	case R.id.one_layout_xiawucha_gallery:
	//	aq.find(R.id.one_layout_text_xiawucha_label).text(String.valueOf(count));
		aq.find(R.id.one_layout_text_xiawucha_select_label).text(String.valueOf(index));
		break;
	case R.id.one_layout_shaokao_gallery:
		//aq.find(R.id.one_layout_text_shaokao_label).text(String.valueOf(count));
		aq.find(R.id.one_layout_text_shaokao_select_label).text(String.valueOf(index));
		break;
	case R.id.one_layout_xianqie_gallery:
		//aq.find(R.id.one_layout_text_xianqie_label).text(String.valueOf(count));
		aq.find(R.id.one_layout_text_xianqie_select_label).text(String.valueOf(index));
		break;
	case R.id.one_layout_xiaochi_gallery:
	//	aq.find(R.id.one_layout_text_xiaochi_label).text(String.valueOf(count));
		aq.find(R.id.one_layout_text_xiaochi_select_label).text(String.valueOf(index));
		break;
	case R.id.one_layout_tianping_gallery:
	//	aq.find(R.id.one_layout_text_tianping_label).text(String.valueOf(count));
		aq.find(R.id.one_layout_text_tianping_select_label).text(String.valueOf(index));
		break;

	default:
		break;
	}
}



public List<GalleryModel> list2gm(List<ZaoDian> l){
	List<GalleryModel> list=new ArrayList<GalleryModel>();
	
	int size=l.size(); 
	GalleryModel g = null;
	
	for (int i = 1; i <= size; i++) {
		if (i%2==1) { 
			g=new GalleryModel();
			g.setFirst(l.get(i-1)); 
			if (i==size) {
				list.add(g);
			}
			
		}else{
			g.setLast(l.get(i-1));	
			list.add(g);
		}
		
	}
	
	return list;
	
}

 
}
